package com.taxinfo.component;

import com.taxinfo.splash.Splash;
import javafx.scene.Parent;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author : Nonoas
 * @time : 2020-09-01 20:58
 */
public class CustomSplash extends Splash {

    private static final String DEFAULT_IMAGE = "images/backdrop.png";

    private static final double DEFAULT_WIDTH = 527d;
    private  boolean flag;

    public CustomSplash() {
//        flag = new File(DEFAULT_IMAGE).exists();

        // 使用ClassLoader的getResourceAsStream方法
        InputStream inputStream = null;
        try {
            inputStream = ResourceLoader.class.getClassLoader().getResourceAsStream(DEFAULT_IMAGE);
            if (inputStream == null) {
                throw new RuntimeException("Failed to load splash image: " + DEFAULT_IMAGE);
            }else {
                flag = true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                inputStream.close();
                inputStream = null;
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }


    // 自定义启动界面图片
    @Override
    public Parent getParent() {

        if (!flag) {
            return super.getParent();
        }

        ImageView imageView = new ImageView(DEFAULT_IMAGE);
        imageView.setFitWidth(DEFAULT_WIDTH);
        imageView.setFitHeight(357);
        imageView.setPreserveRatio(true);

        final ProgressBar splashProgressBar = new ProgressBar();
        splashProgressBar.setPrefWidth(imageView.getFitWidth());
        splashProgressBar.setPrefHeight(4);

        final VBox vbox = new VBox();
        vbox.getChildren().addAll(imageView, splashProgressBar);
        return vbox;
    }

    /**
     * 设置为可见
     */
    @Override
    public boolean visible() {
        return true;
    }

    /**
     * 获取图片路径
     *
     * @return 图片路径
     */
    @Override
    public String getImagePath() {
        if (!flag) {
            return super.getImagePath();
        }
        return DEFAULT_IMAGE;
    }
}
